package org.xqh.utils.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * @ClassName OssDownloadUfils
 * @Description TODO
 * @Author xuqianghui
 * @Date 2020/9/10 15:32
 * @Version 1.0
 */
@Slf4j
public class OssUtils {

    public static String EMPTY_STR = "";

    public static String HTTP_PREFIX = "http://";

    public static String HTTPS_PREFIX = "https://";

//    public static String ossEndPoint = "https://oss-cn-shanghai.aliyuncs.com";
//    public static String bucketName = "shimao-iotpub";
//
//    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
//    public static String accessKeyId = "LTAI4FdYb6pAU2syWxWtz3o6";
//    public static String accessKeySecret = "uYES5sbUsIoNz6ORArDHWizaOCn8KG";

    public static String ossEndPoint = "https://oss-cn-shenzhen.aliyuncs.com";
    public static String bucketName = "ugreen-pro";

    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
    public static String accessKeyId = "LTAI5tJ8MKzkR8MoNtvG2y3H";
    public static String accessKeySecret = "848YXfXBxn9E4Gjzqg56iqiERueGnP";

//    public static void main(String[] args) throws Throwable {
//        // 以华东1（杭州）的外网Endpoint为例，其它Region请按实际情况填写。
//        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
//        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
//        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(new DefaultCredentials(String accessKeyId, String secretAccessKey, String securityToken));
//        // 填写Bucket名称，例如examplebucket。
//        String bucketName = "examplebucket";
//        // 填写Object完整路径，例如exampleobject.txt。Object完整路径中不能包含Bucket名称。
//        String objectName = "exampleobject.txt";
//
//        // 创建OSSClient实例。
//        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
//
//        try {
//            // 设置签名URL过期时间，单位为毫秒。本示例以设置过期时间为1小时为例。
//            Date expiration = new Date(new Date().getTime() + 3600 * 1000L);
//            // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
//            URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
//            System.out.println(url);
//        } catch (OSSException oe) {
//            System.out.println("Caught an OSSException, which means your request made it to OSS, "
//                    + "but was rejected with an error response for some reason.");
//            System.out.println("Error Message:" + oe.getErrorMessage());
//            System.out.println("Error Code:" + oe.getErrorCode());
//            System.out.println("Request ID:" + oe.getRequestId());
//            System.out.println("Host ID:" + oe.getHostId());
//        } catch (ClientException ce) {
//            System.out.println("Caught an ClientException, which means the client encountered "
//                    + "a serious internal problem while trying to communicate with OSS, "
//                    + "such as not being able to access the network.");
//            System.out.println("Error Message:" + ce.getMessage());
//        } finally {
//            if (ossClient != null) {
//                ossClient.shutdown();
//            }
//        }
//    }

    public static void main(String[] args) throws IOException {
        //https://shimao-iotpub.oss-cn-shanghai.aliyuncs.com/template/space/space-import-v2.xlsx  //空间导入模板
//        downFile("E:\\document\\yzs\\program\\shimao-iot\\ab.png", "png/47cac13237a94708a6ec4f3c968f1e17");
          uploadFile(new File("D:\\work\\secureCRT\\upload\\gl.log"), bucketName,
                  "template/space/gl.log");
    }

    public static void uploadFile(File file, String bucketName, String ossKey) throws IOException {
        //ossKey 不能 以 "/" 开头. 否则会报错.
        OSS ossClient = getOssClient();
        byte[] data = FileUtils.readFileToByteArray(file);
        if (data != null && data.length > 0) {
            if (!ossClient.doesBucketExist(bucketName)) {
                log.info("oss create a new bucket==> {}", bucketName);
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest= new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }

            InputStream in = new ByteArrayInputStream(data);
            ossClient.putObject(new PutObjectRequest(bucketName, ossKey, in));
            boolean exists = ossClient.doesObjectExist(bucketName, ossKey);
            log.info("upload to oss result is ==> {}", exists);
            if(exists){
                String url = getOssFileUrl(bucketName, ossEndPoint, ossKey);
                System.out.println(url);
            }
        }
        ossClient.shutdown();
    }

    public static String getOssFileUrl(String bucketName, String endPoint, String filePath){
        boolean returnHttps = false;

        if(endPoint.startsWith(HTTP_PREFIX)){
            endPoint = endPoint.replaceAll(HTTP_PREFIX, "");
            returnHttps = false;
        }

        if(endPoint.startsWith(HTTPS_PREFIX)){
            endPoint = endPoint.replaceAll(HTTPS_PREFIX, "");
            returnHttps = true;
        }

        if(!endPoint.endsWith("/")){
            endPoint = endPoint.concat("/");
        }

        if(filePath.startsWith("/")){
            filePath = filePath.substring(1);
        }

        String returnHttpPrefix = returnHttps ? HTTPS_PREFIX : HTTP_PREFIX;

        return returnHttpPrefix.concat(bucketName).concat(".").concat(endPoint).concat(filePath);

    }

    public static OSS getOssClient(){
        // Endpoint以杭州为例，其它Region请按实际情况填写。
//        String objectName = "<yourObjectName>";

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossEndPoint, accessKeyId, accessKeySecret);
        return ossClient;
    }

    public static void downFile(String filePath, String objectName) {

        OSS ossClient = getOssClient();
// 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
        ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(filePath));

// 关闭OSSClient。
        ossClient.shutdown();
    }
}
